<template>
    <n-card :bordered="false" class="proCard">
      <BasicForm @register="register" @submit="handleSubmit">
        <template #anchorSelect="{ model, field }">
          <n-date-picker
            v-model:formatted-value="model[field]"
            :is-date-disabled="disablePreviousDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            clearable
          />
        </template>
      </BasicForm>
      <BasicTable :columns="columns" :loading="tableLoading" :dataSource="dataSource" :row-key="(row) => row.roleId" :data="true"
                  ref="actionRef"
                  @update:checked-row-keys="onCheckedRow" :pagination="false">
        <template #toolbar>
          <n-button type="primary" @click="downloadExcel">导出账单</n-button>
        </template>   
         
      </BasicTable>
    </n-card>
  </template>
  
  <script lang="ts" setup>
    import {reactive, ref, unref, onMounted,} from 'vue';
    import {c, useMessage} from 'naive-ui';
    import {BasicTable} from '@/components/Table';
    import {columns, fromSchema} from './columns';
    import {useRouter} from 'vue-router';
    import {BasicForm, useForm} from '@/components/Form/index';
    import {getDailyBill} from "@/api/liveBroadcast/dayBill";
    import {formatToDate} from "@/utils/dateUtil";
    import {getChanList} from "@/api/game/chan";
    import {useUserStore} from "@/store/modules/user";
    import BillChart from "../billChart.vue"
    import * as XLSX from 'xlsx'
  
    const message = useMessage();
    const userStore = useUserStore();
    const actionRef = ref();
    const showModal = ref(false);
    const registChanArray = ref([]);
    const anchorOptions = ref([]);
    const dataSource = ref([]);
    const tableLoading = ref(false);
  
    const formParams = reactive<LiveDetailParams>({
      startTime: '',
      endTime: ''
    });

    let json_fields = {
      'date':'日期',
      'cost':'消耗',
      'unitPrice':'单价',
      'oneROI':'首日ROI',
      'totalROI':'总ROI',
      'newRegisterPeople':'新注册',
      'newPayPeople':'新增付费用户',
      'newPayMoney':'新增付费额',
      'newPayCost':'新增付费成本',
      'newPayRate':'新增付费率',
      'newArpu':'新增arpu',
      'newArppu':'新增arppu',
      'activePeople':'活跃用户',
      'payPeople':'付费用户数',
      'payMoney':'总充值金额',
      'activePayRate':'活跃付费率',
      'arpu':'ARPU',
      'arppu':'ARPPU'
    }

    const downloadExcel = ()=> {
      console.log(dataSource)
      // 创建工作表
      let tmp = {
        ARPPU: 0,
        ARPU: 0,
        付费用户数: 0,
        单价: 0,
        总充值金额: 0,
        新增arppu: 0,
        新增arpu: 0,
        新增付费成本: 0,
        新增付费率: 0,
        新增付费用户: 0,
        新增付费额: 0,
        新注册: 0,
        日期: '汇总',
        活跃付费率: 0,
        活跃用户: 0,
        消耗: 0,
        首日ROI: 0,
        总ROI: '/'
      }
      let list = unref(dataSource).map(item => {
        const obj = {}
        for(const k in item) {
          if(json_fields[k]) {
            if(k === 'totalROI') {
              obj[json_fields[k]] = '/'
            }else {
              obj[json_fields[k]] = item[k]
              if(k !== 'date') {
                tmp[json_fields[k]] += parseFloat(item[k])
              }
            }
          }
        }
        return obj
      })
      for(const k in tmp) {
        if(k !== '总ROI' && k !== '日期') tmp[k] = tmp[k].toFixed(2)
      }
      list.push({
        ARPPU: '',
        ARPU: '',
        付费用户数: '',
        单价: '',
        总充值金额: '',
        新增arppu: '',
        新增arpu: '',
        新增付费成本: '',
        新增付费率: '',
        新增付费用户: '',
        新增付费额: '',
        新注册: '',
        日期: '',
        活跃付费率: '',
        活跃用户: '',
        消耗: '',
        首日ROI: '',
        总ROI: ''
      })
      list.push(tmp)
      const data = XLSX.utils.json_to_sheet(list)
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      // 每列不同宽度px
      let wscols = [
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 10 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
            { wch: 12 },
      ];
      data["!cols"] = wscols;
      // 将工作表放入工作簿中
      XLSX.utils.book_append_sheet(wb, data, 'data')
      // 生成文件并下载
      var date = new Date(Date.now())
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
      var strDate = Y + M + D
      XLSX.writeFile(wb, `悠游电竞游戏每日账单(${strDate}).xlsx`)
    }
  
  
    const [register] = useForm({
      gridProps: {cols: '1 s:1 m:2 l:3 xl:4 2xl:4'},
      labelWidth: 120,
      schemas: fromSchema
    });
  
  
    function onCheckedRow(rowKeys: any[]) {
      console.log(rowKeys);
    }
  
    function reloadTable() {
      loadDataSource();
      actionRef.value.reload();
    }
  
  
    async function handleSubmit(values: Recordable) {
      console.log("submit",values);
      let tmp = {
        startTime: values.timeRange[0] ? values.timeRange[0] :'',
        endTime: values.timeRange[1] ? values.timeRange[1] :''
      }
      let tempParams = unref(formParams);
      Object.assign(tempParams, tmp);
      reloadTable()
    }
  
  
    onMounted(async () => {
      tableLoading.value = true;
      try {
        const result = await getDailyBill(formParams);
        console.log('data', result)
        //const anchorInfo = result.anchorInfo;
        //const anchorData = result.chart;
        dataSource.value = unref([]);
        for(let i in result) {
          dataSource.value.push(result[i])
        }
      } finally {
        tableLoading.value = false;
      }
      //loadDataSource()
    });
  
    async function loadDataSource() {
      tableLoading.value = true;
      try {
        const result = await getDailyBill(formParams);
        console.log('data', result)
        //const anchorInfo = result.anchorInfo;
        //const anchorData = result.chart;
        dataSource.value = unref([]);
        for(let i in result) {
          dataSource.value.push(result[i])
        }
      } finally {
        tableLoading.value = false;
      }
    }

    const disablePreviousDate = (ts: number) => {
        return ts > Date.now();
    } 
  </script>
  
  <style lang="less" scoped>
  </style>
  